package com.yxd.demo.rule;

import com.yxd.demo.domain.Coupon;
import com.yxd.demo.dto.CouponDto;
import com.yxd.demo.dto.MutexCouponDto;
import com.yxd.demo.dto.ShareCouponDto;
import com.yxd.demo.service.MarketingWayService;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: yxd
 * @date: 2022/8/8 11:03
 */
@Component(value = "selectRule")
@Rule(name = "选取规则", description = "判断优惠券的最优解", priority = 30)
public class SelectRule {
    @Condition
    public boolean condition(Facts facts) {
        List<Coupon> couponList = facts.get("couponList");
        return !CollectionUtils.isEmpty(couponList);
    }

    @Action
    public void action(Facts facts) {
        List<Coupon> couponList = facts.get("couponList");
        List<Coupon> mutexList = new ArrayList<>();
        List<Coupon> shareList = new ArrayList<>();
        BigDecimal shareDiscountPrice = null;
        BigDecimal mutexDiscountPrice = null;
        Long mutexId = null;
        for (Coupon coupon : couponList) {
            Integer mutex = coupon.getMutex();
            BigDecimal discountPrice = coupon.getDiscountPrice();
            if (Objects.equals(1, mutex)) {
                mutexList.add(coupon);
                if (MarketingWayService.compareTo(mutexDiscountPrice, discountPrice)) {
                    continue;
                }
                mutexId = coupon.getId();
                mutexDiscountPrice = discountPrice;
            } else {
                shareList.add(coupon);
                shareDiscountPrice = MarketingWayService.add(shareDiscountPrice, discountPrice);
            }
        }
        facts.put("couponDto", CouponDto.builder()
                .mutexCouponDto(MutexCouponDto.builder()
                        .mutexCouponList(mutexList.stream().sorted(Comparator.comparing(Coupon::getDiscountPrice).reversed()).collect(Collectors.toList()))
                        .couponId(mutexId)
                        .totalDiscountPrice(mutexDiscountPrice)
                        .build())
                .shareCouponDto(ShareCouponDto.builder()
                        .totalDiscountPrice(shareDiscountPrice)
                        .shareCouponList(shareList.stream().sorted(Comparator.comparing(Coupon::getDiscountPrice).reversed()).collect(Collectors.toList()))
                        .build())
                .optimal(MarketingWayService.compareTo(shareDiscountPrice, mutexDiscountPrice) ? 1 : 2)
                .build());
    }
}
